package com.wn.ticket.security;

import com.wn.ticket.common.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @创建人 NST
 * @创建时间 2022/8/22
 * @描述
 */
@Slf4j
public class FrontJwtFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private FrontUserDetailsService frontUserDetailsService;

    private AuthenticationFailureHandler authenticationFailureHandler;

    public FrontJwtFilter(JwtUtils jwtUtil, AuthenticationFailureHandler authenticationFailureHandler) {
        this.jwtUtils = jwtUtil;
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if(request.getRequestURI().contains("png")||request.getRequestURI().contains("jpg")||request.getRequestURI().contains("QRcode")||request.getRequestURI().contains("backstage")){
            filterChain.doFilter(request, response);
            return;
        }
        if (token == null) {
            authenticationFailureHandler.onAuthenticationFailure(request, response, new JwtException("token为空"+request.getRequestURI()));
            return;
        }
        if (!jwtUtils.verifySecretJWT(token)) {
            authenticationFailureHandler.onAuthenticationFailure(request, response, new JwtException("token无效"));
            return;
        }
        if (!jwtUtils.verifyTimeJWT(token)) {
            authenticationFailureHandler.onAuthenticationFailure(request, response, new JwtException("token已过期"));
            return;
        }

        String account = (String) jwtUtils.getInfo(token, "account");
        UserDetails userDetails = frontUserDetailsService.loadUserByUsername(account);
        //验证成功后生成UsernamePasswordAuthenticationToken,,这里密码为null，是因为提供了正确的JWT,实现自动登录
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}

